package com.haifeng.wdsh.common.datasource.handler;

import com.haifeng.wdsh.common.base.exception.BusinessException;
import com.haifeng.wdsh.common.base.util.Rest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常捕获
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 处理异常
     */
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Rest<Object> globalException(Exception e, HttpServletResponse response) {
        Rest<Object> restfulMessage = new Rest<>();
        restfulMessage.setSuccess(false);
        if (e instanceof BusinessException) {
            //手动抛出的业务异常
            BusinessException exception = (BusinessException) e;
            restfulMessage.setCode(exception.getErrCode());
            restfulMessage.setMessage(exception.getMessage());
        } else {
            //其他异常
            restfulMessage.setCode(response.getStatus());
            restfulMessage.setMessage(e.getMessage());
        }
        log.error("【项目发生异常：】" + restfulMessage.toString());
        e.printStackTrace();
        return restfulMessage;
    }
}
